package org.ms.nerver.governor.fault.proxy;

import java.lang.reflect.Method;

import org.ms.nerver.governor.proxy.CglibAbstractProxyFactory;

public class CglibFaultProxyFactory extends CglibAbstractProxyFactory {

	//private Logger logger=Logger.getLogger(CglibFaultProxyFactory.class);
	
	public CglibFaultProxyFactory(Object obj) {
		super(obj);
	}

	public void doBefore(Object proxy, Method method, Object[] args) {

	}
	
	/**
	 * 调度执行
	 */
	public Object doInvoke(Method method, Object proxy, Object[] args,Object...others) throws Throwable {
		Object result=null;
		
//		MethodProxy methodProxy=null;
//		if(others!=null){
//			for (Object object:others) {
//				if(object instanceof MethodProxy){
//					methodProxy=(MethodProxy) object;
//					break;
//				}
//				
//			}
//		}
//		Method implMethod=proxy.getClass().getMethod("CGLIB$add$0", method.getParameterTypes());
//		if(implMethod!=null){
//			FT ft=implMethod.getAnnotation(FT.class);
//			if(ft!=null){//开启容错机制
//				//周期性重试
//				int retryTimes=ft.retryTimes();
//				if(retryTimes<1){
//					throw new Throwable("'retryTimes' must be greater than 0.");
//				}
//				while (retryTimes-->0) {
//					try {
//						return methodProxy.invokeSuper(proxy, args);
//					} catch (Throwable e) {
//						logger.debug("调度重试第"+(ft.retryTimes()-retryTimes)+"次");
//						if(retryTimes==0){//失败完毕
//							if(ft.fallbackMethod()==null||"".equals(ft.fallbackMethod())){//校验,抛出异常
//								throw new Throwable("Invoke ["+method+"] was not found.");
//							}
//						}
//					}
//				}
//				
//				Method failbackImplMethod=proxy.getClass().getMethod(ft.fallbackMethod(), method.getParameterTypes());
//				if(failbackImplMethod!=null){
//					//周期性容错
//					int fallbackRetryTimes=ft.fallbackRetryTimes();
//					if(fallbackRetryTimes<1){
//						throw new Throwable("'fallbackRetryTimes' must be greater than 0.");
//					}
//					while (fallbackRetryTimes-->0) {
//						try {
//							return failbackImplMethod.invoke(proxy, args);
//						} catch (Throwable e) {
//							logger.debug("容错重试第"+(ft.fallbackRetryTimes()-fallbackRetryTimes)+"次");
//							if(fallbackRetryTimes==0){//抛出异常
//								throw new Throwable("Failback Invoke ["+method+"] was not found.");
//							}
//						}
//					}
//				}else{
//					throw new Throwable("Failback method ["+failbackImplMethod+"] was not found.");
//				}
//			}else{//未开启容错,则直接调度
//				return super.doInvoke(implMethod, proxy, args,others);
//			}
//		}else{
//			throw new Throwable("Invoke ["+method+"] was not found.");
//		}
		return result;
	}

	public void doAfter(Object proxy, Method method, Object[] args, Object result) {

	}

	

}
